<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 添加角色区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="AddRoleDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表区域 -->
      <el-table :data="roleList" border stripe >
          <!-- 往下展开的按钮列 -->
          <el-table-column type="expand">
              <template v-slot="scope">
                <el-row v-for="(item,index) in scope.row.children" :key="item.id" :class="['item-bottom',index===0? 'item-top':'','item-ycenter']">
                    <!-- 渲染一级权限 -->
                    <el-col :span="5" >
                        <el-tag closable @close="removeRightById(scope.row,item.id)">{{item.authName}}</el-tag>
                        <!-- 小箭头 -->
                        <i class="el-icon-caret-right"></i>
                    </el-col>
                    <!-- 渲染二级和三级权限 -->
                    <el-col :span='19'>
                         <el-row v-for="(item2,index) in item.children" :key="item2.id" :class="[index === 0 ? '' : 'item-top','item-ycenter']">
                            <el-col :span="10">
                                <el-tag closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <el-col :span="14">
                                <el-tag v-for="item3 in item2.children " :key="item3.id" closable @close="removeRightById(scope.row,item3.id)">{{item3.authName}}</el-tag>
                            </el-col>
                        </el-row>
                    </el-col>
                </el-row>
              </template>
          </el-table-column>
          <el-table-column type="index"></el-table-column>
          <el-table-column label="角色名称" prop="roleName"></el-table-column>
          <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
          <el-table-column label="操作" width="400px">
              <template v-slot='scope'>
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="editRole(scope.row.id)">编辑</el-button>
                <el-button type="success" icon="el-icon-delete" size="mini" @click="deleteRole(scope.row.id)">删除</el-button>
                <el-button type="info" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配</el-button>
              </template>
          </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="AddRoleDialogVisible" width="40%" @close="AddRoleDialogClose">
       <el-form
        :model="addRoleForm"
        ref="addRoleFormRef"
        :rules="addRoleFormRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="AddRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog title="编辑角色" :visible.sync='editRoleDialogVisible' width="40%">
      <el-form :model="editRoleForm" ref="editRoleFormRef" :rules="editRoleFormRules" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editRoleDialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="editRoleCommit">编 辑</el-button>
      </span>
    </el-dialog>

  <!-- 分配权限对话框 -->
    <el-dialog
  title="分配权限"
  :visible.sync="setRightDialogVisible"
  width="50%"
  @close='setRoleDialogClose'
  >
  <el-tree :data="rightsList" :props="treeProps" show-checkbox
  node-key="id"  ref="rightsTree"
  default-expand-all :default-checked-keys="defaultKeys">
  </el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRightDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表数据
      roleList: [],
      // 添加角色对话框
      AddRoleDialogVisible: false,
      // 角色对象
      addRoleForm: {},
      // 添加角色预校验规则
      addRoleFormRules: {
        roleName: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ],
        roleDesc: [{
          required: true, message: '描述不能为空', trigger: 'blur'
        }]
      },
      // 编辑角色对话框
      editRoleDialogVisible: false,
      // 编辑角色的对象
      editRoleForm: {},
      // 编辑对象的表单教研规则
      editRoleFormRules: {
        roleName: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '描述不能为空', trigger: 'blur' }
        ]
      },
      // 分配权限对话框是否显示
      setRightDialogVisible: false,
      // 分配角色按钮的权限数据
      rightsList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        // 树形结构父子节点嵌套的属性
        children: 'children',
        // 显示的文本
        label: 'authName'
      },
      // 角色有的权限的id值
      defaultKeys: [],

      // 提交角色授权接口所需要的id
      roleId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('角色列表获取失败')
      this.roleList = res.data
      console.log(this.roleList, '角色列表数据')
    },

    // 添加角色方法
    addRoles() {
      this.$refs.addRoleFormRef.validate(async result => {
        if (!result) return
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        console.log(res, 'res数据是')
        if (res.meta.status !== 201) { this.$message.error('添加角色失败') } else { this.$message.success('添加角色成功') }
        this.AddRoleDialogVisible = false
        this.getRolesList()
      })
    },
    // 添加角色对话框关闭后触发的方法
    AddRoleDialogClose() {
      this.$refs.addRoleFormRef.resetFields()
    },
    // 编辑角色按钮
    async editRole(id) {
      // 接口规定id参数要携带带url中
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('根据id查询角色失败')
      this.editRoleForm = res.data
      this.editRoleDialogVisible = true
    },

    // 确定编辑角色
    editRoleCommit() {
      this.$refs.editRoleFormRef.validate(async result => {
        if (!result) return
        const { data: res } = await this.$http.put('roles/' + this.editRoleForm.Id, {
          roleName: this.editRoleForm.roleName,
          roleDesc: this.editRoleForm.roleDesc
        })
        if (res.meta.status !== 200) { return this.$message.error('编辑提交角色失败', res.meta.status) }
        this.$message.success('编辑角色成功')
        this.editRoleDialogVisible = false
        this.getRolesList()
      })
    },

    // 删除角色
    deleteRole(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        // 是否圆角
        roundButton: true,
        // 是否居中布局
        center: true
      }).then(() => {
        this.$http.delete('roles/' + id).then(res => {
          if (res.data.meta.status !== 200) return this.$message.error('删除角色失败')
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getRolesList()
        }).catch(error => this.$message.error(error))
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 删除角色id的某个权限
    async removeRightById(role, rightId) {
    //  弹窗提示用户
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {})
      // 如果不是reslove返回confirm字符串，就是用户取消了删除操作
      if (confirmResult !== 'confirm') return this.$message.info('取消删除')

      // 删除角色id的某个权限
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$message.error('删除权限失败')

      // this.getRolesList() 重新请求数据会自动合上页面
      // 重新把服务器返回的数据给role.children 就不会刷新合上
      role.children = res.data
    },

    // 展示分配权限对话框
    async showSetRightDialog(role) {
      this.roleId = role.id
      // 获取所有权限的数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限数据失败')
      this.rightsList = res.data
      console.log(this.rightsList, 'rightsList')

      // 拿到角色对应的三级权限信息,保存到defaultKeys
      this.getRoleRights(role, this.defaultKeys)

      this.setRightDialogVisible = true
    },

    // 获取角色所有的权限id 并保存到arr中
    getRoleRights(node, arr) {
      // 是第三级权限的话：
      if (node.children == null) {
        arr.push(node.id)
      } else {
        // 每个数组的元素都做成参数去调用这个方法 递归一次或者两次
        node.children.forEach(element => {
          this.getRoleRights(element, arr)
        })
      }
    },

    // 清空一下当前保存的权限id数据defaultKeys 才不会影响下一次点击
    setRoleDialogClose() {
      this.defaultKeys = []
    },

    // 分配权限对话框点击确认按钮，触发的逻辑
    async allotRights() {
      // 拿到当前tree中选定的权限
      const tempRightsArr = [
        ...this.$refs.rightsTree.getCheckedKeys(),
        ...this.$refs.rightsTree.getHalfCheckedKeys()
      ]
      // 接口要求要一个,拼接的id字符串
      const tempRightsStr = tempRightsArr.join(',')
      // 路徑地址也可以寫成`roles/${this.roleId}/rights`
      // roleID點擊出現對話框的時候就保存到data裡面樂
      const { data: res } = await this.$http.post('roles/' + this.roleId + '/rights', { rids: tempRightsStr })
      if (res.meta.status !== 200) return this.$message.error('分配角色權限失敗')
      else this.$message.success('分配成功')
      this.getRolesList()
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 20px;
}
.el-table{
    margin-top: 20px;
}
.item-top{
    border-top: 1px  solid #eee;
}
.item-bottom{
    border-bottom:  1px solid #eee;
}
.el-tag{
    margin: 7px;
}

.item-ycenter{
  display: flex;
  align-items: center;
}
</style>
